home *** CD-ROM | disk | FTP | other *** search
/ Internet Info 1994 March / Internet Info CD-ROM (Walnut Creek) (March 1994).iso / networking / info-service / wais / ir-book-sources / mphf / pmrandom.c < prev    next >
C/C++ Source or Header  |  1993-04-08  |  2KB  |  83 lines

  1. /******************************  pmrandom.h  ***************************
  2.  
  3.   Purpose:    Implement a random-number generator package for this program.
  4.  
  5.   Provenance:    Written and tested by Q. Chen and E. Fox, March 1991.
  6.           Edited by S. Wartik, April 1991.
  7.  
  8.   Notes:    It is assumed that the C data type "int" can store
  9.           32-bit quantities.
  10. **/
  11.  
  12. #include "pmrandom.h"
  13.  
  14. static int seed = DEFAULT_SEED;     /* The seed of the random number generator.    */
  15.  
  16. /*************************************************************************
  17.  
  18.     setseed(int)
  19.  
  20.    Returns:    int
  21.  
  22.    Purpose:    Set the seed for the random number generator.
  23.  
  24.    Plan:    Uses a formula suggested by Park and Miller.  See above.
  25.  
  26.    Notes:    None.
  27. **/
  28.  
  29. void setseed( new_seed )
  30.     int    new_seed;
  31. {
  32.     int    low, high, test;
  33.  
  34.     if ( (new_seed < 1) || (new_seed > 2147483646) )
  35.     new_seed = DEFAULT_SEED;
  36.     high = new_seed / 127773;        /* 127773 = 2147483647 div 16807 */
  37.     low  = new_seed % 127773;
  38.     test = 16807 * low - 2836 * high;    /* 2836 = 2147483647 mod 16807   */
  39.     seed = ( test > 0 ) ? test : test + 2147483647;
  40. }
  41.  
  42.  
  43. /*************************************************************************
  44.  
  45.        pmrandom()
  46.  
  47.    Returns:    void
  48.  
  49.    Purpose:    Return the next random number in the sequence.
  50.  
  51.    Plan:    Uses the formula:
  52.  
  53.             f() = ( 16807 * seed ) mod 2147483647.
  54.  
  55.         The value of "seed" must be within [1, ..., 2147483646].
  56.  
  57.    Notes:    None.
  58. **/
  59.  
  60. int pmrandom()
  61. {
  62.     int    tmp = seed;
  63.  
  64.     setseed(seed);
  65.     return(tmp);
  66. }
  67.  
  68. /***********************************************************************
  69.  
  70.       getseed()
  71.  
  72.   Returns:    int
  73.  
  74.   Purpose:    Get the current value of the seed.
  75.  
  76.   Notes:    None.
  77. **/
  78.  
  79. int getseed()
  80. {
  81.     return (seed);
  82. }
  83.